import { createRouter, createWebHashHistory } from "vue-router";

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),

  routes: [
    {
      path: "/",
      name: "home",
      component: () => import("@/components/layout/index.vue"),
      redirect: "/comment",
      children: [
        {
          path: "/chart/:id",
          name: "chart",
          component: () => import("@/views/echart/index.vue"),
          meta: { title: '数据管理' },
        },
        {
          path: "/remote",
          name: "remote",
          component: () => import("@/views/remote/index.vue"),
          meta: { title: '远程控制' },
        },
        {
          path: "/comment",
          name: "comment",
          component: () => import("@/views/comment/uitl.vue"),
          meta: { title: '菜单组件' },
        }
      ],
    },
    {
      path: "/login",
      name: "login",
      component: () => import("../views/login/index.vue"),
      meta: { 
        title: '登录',
        requiresAuth: false
      }
    },
    {
      path: "/:pathMatch(.*)*",
      name: "NotFound",
      component: () => import("@/views/comment/404.vue"),
      meta: { title: '页面未找到' }
    }
  ],
});

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem("token");
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 数据管理系统` : '数据管理系统';
  
  // 判断页面是否需要认证
  if (to.meta.requiresAuth) {
    if (!token) {
      // 需要认证但没有token，跳转到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 保存原目标路径
      });
      return;
    }
  } else if (to.path === '/login' && token) {
    // 已登录用户访问登录页，重定向到首页
    next('/comment');
    return;
  }

  next();
});

export default router;
